package com.sunshine.lnuplus.view.Timetable;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.snackbar.Snackbar;
import com.sunshine.lnuplus.R;
import com.sunshine.lnuplus.utils.DatabaseHelper;
import com.sunshine.lnuplus.utils.DialogFragmentHelper;
import com.sunshine.lnuplus.utils.LessonDetailHelper;
import com.sunshine.lnuplus.utils.TagHelper;
import com.sunshine.lnuplus.view.AddLesson.AddLessonActivity;
import com.sunshine.timetable.TimetableView;

public class EveryWeekTimetableFragment extends Fragment {

    private TimetableView timetableView;
    private SharedPreferences timetableSetting;

    /**
     * 这个可以在创建view前来设置信息
     * @param id
     * @return
     */
    public static EveryWeekTimetableFragment newInstance(int id){
        Bundle bundle = new Bundle();
        bundle.putInt("week",id);
        EveryWeekTimetableFragment fragment = new EveryWeekTimetableFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_every_week_timetable, container, false);
        timetableView = view.findViewById(R.id.timetable_layout);
        timetableSetting = getActivity().getSharedPreferences("timetable_setting", Context.MODE_PRIVATE);

        //注意这个不可以在onActivityCreated中设置否则会空界面
        timetableView
                .setThisWeek(getArguments().getInt("week"))
                .setShowWeekend(timetableSetting.getBoolean("show_weekend",true))
                .setLessonCount(timetableSetting.getInt("lesson_count",5))
                .setHeights(timetableSetting.getInt("heights",300))
                .setShowTeacher(timetableSetting.getBoolean("show_teacher",true))
                .setShowNotInThisWeekLesson(timetableSetting.getBoolean("show_not_in_this_week_lesson",true))
                .setButtonAlpha(timetableSetting.getInt("button_alpha", 255))
                .setButtonRadius(timetableSetting.getInt("button_radius",20))
                .setButtonHeightDistance(timetableSetting.getInt("button_height_distance",10))
                .setButtonWidthDistance(timetableSetting.getInt("button_width_distance",10))
                .setButtonHeightPadding(timetableSetting.getInt("button_height_padding",5))
                .setButtonWidthPadding(timetableSetting.getInt("button_width_padding",5))
                .setDateButtonTextSize(timetableSetting.getFloat("date_button_text_size",12f))
                .setTimeButtonTextSize(timetableSetting.getFloat("time_button_text_size",11f))
                .setLessonButtonTextSize(timetableSetting.getFloat("lesson_button_text_size",11f))
                .setShowLessonTime(timetableSetting.getBoolean("show_lesson_time",true))
                .initTimetable()
                .addLesson(TimetableFragment.getTimetable());
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setButtonOnClick();
    }

    private void setButtonOnClick() {
        for(int day = 0;day<timetableView.getDayCount();day++){
            for(int quart = 0;quart<timetableView.getLessonCount();quart++){
                final int finalDay = day;
                final int finalQuart = quart;
                final String lessonInfo = timetableView.getLessonesButton().get(day).get(quart).getText().toString();
                final String time = (day+1)+"-"+(quart+1);

                timetableView.getLessonesButton().get(day).get(quart).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(lessonInfo.equals("")){
                            Bundle bundle = new Bundle();
                            bundle.putString("lesson_name","");
                            bundle.putString("teacher","");
                            bundle.putString("room","");
                            bundle.putString("time",time);
                            bundle.putString("color","0");
                            bundle.putString("weeks","");
                            bundle.putBoolean("add",true);
                            startActivityForResult(new Intent(getActivity(), AddLessonActivity.class).putExtras(bundle), TagHelper.EVERYDAY);
                        }else {
                            LessonDetailHelper detailHelper = LessonDetailHelper.newInstance(timetableView.getLessonesText().get(finalDay).get(finalQuart).toString(),time,EveryWeekTimetableFragment.this);
                            detailHelper.show(getChildFragmentManager(),"");
                        }
                    }
                });

                timetableView.getLessonesButton().get(day).get(quart).setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if(!lessonInfo.equals("")){
                            final String[] lesson = timetableView.getLessonesText().get(finalDay).get(finalQuart).toString().split("\n");
                            if(lesson.length>1){
                                initDeleteMultiDialog(lesson,time);
                            }else {
                                Snackbar.make(getView(),"你真的要删除这节课吗？删除就不能恢复了~",Snackbar.LENGTH_LONG)
                                        .setAction("给我删除！", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                DatabaseHelper.deleteTimetableFromDB(getContext(),timetableView.getLessonesText().get(finalDay).get(finalQuart).toString().split("\n")[0],time);
                                                DatabaseHelper.deleteCountDownFromDB(getContext(),timetableView.getLessonesText().get(finalDay).get(finalQuart).toString().split("\n")[0]);
                                                timetableView.initTimetable().addLesson(TimetableFragment.getTimetable());
                                                setButtonOnClick();
                                                Snackbar.make(getView(),getString(R.string.lesson_delete_success),Snackbar.LENGTH_SHORT).show();
                                            }
                                        }).show();
                            }
                        }
                        return true;
                    }
                });
            }
        }
    }

    private void initDeleteMultiDialog(final String[] lesson, final String time){
        final boolean[] deleteBoolean = new boolean[lesson.length];
        DialogInterface.OnMultiChoiceClickListener onMultiChoiceClickListener = new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                deleteBoolean[which] = isChecked;
            }
        };
        DialogInterface.OnClickListener positive = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for(int i = 0;i<lesson.length;i++){
                    if(deleteBoolean[i]){
                        DatabaseHelper.deleteTimetableFromDB(getContext(),lesson[i],time);
                        DatabaseHelper.deleteCountDownFromDB(getContext(),lesson[i]);
                    }
                }
                timetableView.initTimetable().addLesson(TimetableFragment.getTimetable());
                setButtonOnClick();
                Snackbar.make(getView(),getString(R.string.lesson_delete_success),Snackbar.LENGTH_SHORT).show();
            }
        };
        DialogInterface.OnClickListener negative = new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) { }};
        DialogFragmentHelper dialogFragmentHelper = DialogFragmentHelper.newInstance("这个时间有"+lesson.length+"节课，你要删除哪一个呢","确定","取消",false,lesson,onMultiChoiceClickListener,deleteBoolean,positive,negative);
        dialogFragmentHelper.show(getFragmentManager(),"");
    }

    public void updateTimetable(){
        timetableView.initTimetable().addLesson(TimetableFragment.getTimetable());
        setButtonOnClick();
        Snackbar.make(getView(),"修改成功，如果没有及时更新点击下方“课表”按钮刷新~",Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== TagHelper.ADDLESSON){
            timetableView.initTimetable().addLesson(TimetableFragment.getTimetable());
            setButtonOnClick();
            Snackbar.make(getView(),"修改成功，如果没有及时更新点击下方“课表”按钮刷新~",Snackbar.LENGTH_SHORT).show();
        }
    }

}
